<template>
  <div class="content">
    <el-card class="content-card">
      <div slot="header" class="content-card-header">
        <span>修改密码</span>
      </div>
      <div class="content-card-body">
        <el-form ref="ruleForm" label-width="110px" :model="form" :rules="rules">
          <el-form-item label="当前密码" prop="currentPassword">
            <el-input v-model="form.currentPassword" type="password" />
          </el-form-item>
          <el-form-item label="新密码" prop="password">
            <el-input v-model="form.password" type="password" />
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input v-model="form.confirmPassword" type="password" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="medium" @click="handleUpdate">确认修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { update } from '@/api/admin'

export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '' || value === undefined) {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      form: {
        currentPassword: '',
        password: '',
        confirmPassword: ''
      },
      rules: {
        currentPassword: { required: true, message: '密码不能为空', trigger: 'change' },
        password: { required: true, message: '密码不能为空', trigger: 'change' },
        confirmPassword: [
          { required: true, message: '密码不能为空', trigger: 'change' },
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 更新操作
    handleUpdate() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const md5Form = { password: this.$md5(this.form.password), currentPassword: this.$md5(this.form.currentPassword) }
          update(md5Form).then(response => {
            if (response.code === 200) {
              // 退出登录
              this.$store.dispatch('user/logout', md5Form).then(() => {
                this.$router.push({ path: this.redirect || '/' })
              })
            } else {
              this.$message({
                type: 'error',
                message: response.message
              })
            }
          })
        } else {
          this.$message({
            type: 'error',
            message: '输入有误，请重新检查'
          })
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
  .content {
    padding: 7.5px;
  }

  .content-card-header:before,
  .content-card-header:after {
    display: table;
    content: "";
  }
  .content-card-header:after {
    clear: both
  }

  .content-card-body {
    width: 460px;
  }
</style>
